<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +---------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace cmf\controller;
use think\Db;
use app\common\lib\user_operate\ModuleOperate;

class PluginAdminBaseController extends PluginBaseController
{

    // 初始化
    protected function _initialize()
    {
        //检查插件是否安装
        $pluginName =ucwords(cmf_parse_name($this->request->param('_plugin'), $type = 1));

        // $code = Db::name('auth_access')->where('rule_name','like','%'.'plugin/'.$pluginName.'/%')->find();

        // $mo = new ModuleOperate();
        // //是否安装
        // $is_succ = $mo->installStatus($pluginName,$code['code']);
        // if ($is_succ['status'] != 'success') {
        //     $this->error($is_succ['message']);
        // }

        $adminId = cmf_get_current_admin_id();
        if (!empty($adminId)) {
            if (!$this->checkAccess($adminId)) {
                $this->error("您没有访问权限！");
            }
        } else {
            if ($this->request->isAjax()) {
                $this->error("您还没有登录！", url("admin/Public/login"));
            } else {
                header("Location:" . url("admin/Public/login"));
                exit();
            }
        }
    }

    /**
     *  检查后台用户访问权限
     * @param int $userId 后台用户id
     * @return boolean 检查通过返回true
     */
    private function checkAccess($userId)
    {

        $role = \app\common\lib\AccessAuthorization::getHighestRoleInfo( $userId );

        $attach = Db::name('user_attach')->where( 'user_id' , $userId )->find();

        //如果是最高角色
        if( isset( $role [ 'id' ] ) && isset( $attach [ 'role_id' ] ) && $role [ 'id' ] == $attach [ 'role_id' ] ){
            return true;
        }

        /*// 如果用户id是1，则无需判断
        if ($userId == 1) {
            return true;
        }*/
        
        $pluginName = cmf_parse_name( $this->request->param('_plugin') , 1 );
        $controller = $this->request->param('_controller');
        $controller = cmf_parse_name($controller, 1);
        $action     = $this->request->param('_action');       
        return cmf_auth_check($userId, "plugin/{$pluginName}/$controller/$action");
    }


}